<?php

/**
 * 工作便函
 * @author ZhouYP
 * */

namespace Admin\Controller;

use Common\Controller\WahahabaseController;

class WorkingMemoController extends WahahabaseController {

    protected $dept_model;
    protected $department_model;
    protected $consignee_model;

    public function _initialize() {
        parent::_initialize();
        $this->deal_model = D("Common/WorkingMemo");
        $this->dept_model = D("Common/Department");
        $this->department_model = D("Common/Department");
        $this->consignee_model = D("Common/Consignee");
        $this->att_model = D("Common/Attachment");
    }

    public function indexPage($where) {
        $eq = array(
            "eq" => "=",
            "neq" => "!=",
            "gt" => ">",
            "egt" => ">=",
            "lt" => "<",
            "elt" => "<=",
            "like" => "LIKE"
        );
        // 当前登录人
        $adminId = session('ADMIN_ID');
        $adminGroup = getUserInfo($adminId);

        $condition = "d.is_deleted <> 1 ";
        //$condition .= session('deptid') == 0 ? " AND (1 = 1 " : " AND ((SELECT department_role FROM hzzy_department WHERE id='" . session("deptid") . "') = 1 ";
        //发布人
        $condition .= " OR (1 = 0 ";
        //查看主送或抄送
        $condition .= "OR ('" . session("deptid") . "' IN 
        (SELECT department_id FROM hzzy_consignee WHERE table_id = d.id AND belong_to='1'))) 
       ";
        //当前发布的所属部门等于当前用户的所属部门    或    假设发布人的权限为2级，当前用户是1级。  2 > 1 ： 所以当前用户有权限.
        // $condition .= " OR d.add_department= '$adminGroup[department_id]' OR 
        //               Com.department_role > '$adminGroup[department_role]' AND '$adminGroup[department_role]' in ('1','2','3'))";
        // $condition .= " AND d.is_publish = '1' ";
        //权限设置 20171228
        $condition .= " AND (
            (d.is_publish = 0 AND (d.add_user = $adminId OR ((SELECT department_id FROM hzzy_users WHERE id=$adminId) = d.add_department) AND ((SELECT role_id FROM hzzy_users WHERE id=$adminId) IN('1','2','3'))))
            OR
            (d.is_publish = 1   
                AND (
                        (SELECT IFNULL(department_role,0) as `level` FROM hzzy_users u1 LEFT JOIN hzzy_department d1 ON u1.department_id = d1.id WHERE u1.id=$adminId)
                        <= 
                        (SELECT IFNULL(department_role,0) as `level` FROM hzzy_users u2 LEFT JOIN hzzy_department d2 ON u2.department_id = d2.id WHERE u2.id=d.add_user)
                )
                AND  '$adminGroup[department_role]' in ('1','2','3')
                OR ((SELECT department_id FROM hzzy_users WHERE id=$adminId) = d.add_department)
            )
            OR
            ((SELECT role_id FROM hzzy_users WHERE id=$adminId) = 0 AND d.is_publish = 1)
        )";

        foreach ($where as $key => $v) {
            if (count($v) > 1) {
                $d = $eq[$v[0]] == NULL ? '=' : $eq[$v[0]];
                if ($d != 'LIKE') {
                    $condition .= " AND $key $d '" . $v[1] . "'";
                } else {
                    $condition .= " AND $key $d '%" . $v[1] . "%'";
                }
            } else {
                $condition .= " AND $key = '$v'";
            }
        }
        $count = $this->deal_model->alias("d")
                ->join(array(
                    ' LEFT JOIN ' . C('DB_PREFIX') . 'users u ON d.add_user = u.id',
                    ' LEFT JOIN ' . C('DB_PREFIX') . 'department Com ON u.department_id = Com.id'
                ))
            ->where($condition)->count();
        $page = $this->page($count, 20);

        $results = $this->deal_model->alias("d")
                ->field('d.*,u.real_name')
                ->join(array(
                    ' LEFT JOIN ' . C('DB_PREFIX') . 'users u ON d.add_user = u.id',
                    ' LEFT JOIN ' . C('DB_PREFIX') . 'department Com ON u.department_id = Com.id'
                ))
                ->where($condition)
                ->order("d.add_time DESC")
                ->limit($page->firstRow, $page->listRows)
                ->select();
        //exit($this->deal_model->getLastSql());    
        $this->assign("page", $page->show('Admin'));
        $this->assign("results", $results);

        $this->display();
    }

    /**
     *  主页
     */
    public function index() {
        /*         * 搜索条件* */
        $where = array("d.is_deleted" => array('eq', 0));
        $title = trim(I('request.title'));
        if ($title) {
            $where['title'] = array('like', "%$title%");
        }
        $this->getDepartLevel();
        $this->indexPage($where);
    }

    /**
     *  添加工作便函
     */
    public function add() {
        //显示抄送数据
        $Department = $this->department_model->where(array('is_deleted' => 0))->field("id,department_name")->order("id DESC")->select();
        $this->assign("data", $Department);
        // 默认为浙江泛华工程监理有限公司
        $SelectDefault = 5;
        $this -> assign('selectDefault',$SelectDefault);
        $this->display();
    }

    public function add_post() {
        if (IS_POST) {
            // 合并底层数据
            $data = array_merge($_POST, $this->saveData());
            if ($this->deal_model->create() !== false) {
                $result = $this->deal_model->add($data);
                if ($result !== false) {
                    //上传文件  工作便函:17
                    $this->saveFile($result, 17);
                    $cons = array(
                        "belong_to" => '1',
                        "table_id" => $result
                    );
                    foreach ($data['carbon_copy_department'] as $key => $vo) {
                        $cons['consignee_type'] = '2';
                        $cons['department_id'] = $vo;
                        $this->consignee_model->add($cons);
                    };
                    if(I('post.department_id')){
                        $cons['consignee_type'] = '1';
                        $cons['department_id'] = I('post.department_id');
                        $this->consignee_model->add($cons);
                    }
                    $this->success("添加成功！", U("WorkingMemo/index"));
                } else {
                    $this->error("添加失败！");
                }
            } else {
                $this->error($this->deal_model->getError());
            }
        }
    }

    public function view() {
        $this->getDepartLevel();
        $this->getinfo();
    }

    /**
     *  修改工作便函
     */
    public function edit() {
        $this->getinfo();
    }

    public function edit_post() {
        if (IS_POST) {
            $data = array_merge($_POST, $this->saveData(2));
            if ($this->deal_model->create() !== false) {
                $result = $this->deal_model->save($data);
                if ($result !== false) {
                    //上传文件  工作便函:17
                    $this->saveFile(I("post.id"), 17, 2);
                    $this->consignee_model->where(array('belong_to' => 1, 'table_id' => I("post.id", 0)))->delete();
                    $cons = array(
                        "belong_to" => '1',
                        "table_id" => I("post.id", 0)
                    );
                    foreach ($data['carbon_copy_department'] as $key => $vo) {
                        $cons['consignee_type'] = '2';
                        $cons['department_id'] = $vo;
                        $this->consignee_model->add($cons);
                    };
                    if(I('post.department_id')){
                        $cons['consignee_type'] = '1';
                        $cons['department_id'] = I('post.department_id');
                        $this->consignee_model->add($cons);
                    }
                    $this->success("保存成功！", U("WorkingMemo/index"));
                } else {
                    $this->error("保存失败！");
                }
            } else {
                $this->error($this->deal_model->getError());
            }
        }
    }

    /**
     * 获取一条数据
     * */
    public function getinfo() {
        $id = I('get.id', 0, 'intval');
        $work = $this->deal_model->alias("d")
                ->field('d.*')
                ->where(array("d.id" => $id))
                ->find();
        $this->assign("result", $work);
        $this -> assign('selectDefault',$work['add_department']);

        //exit($this->deal_model->getLastSql());
        $Department = $this->department_model->field("id,department_name")->where(array("is_deleted" => array('neq', 1)))->order("id DESC")->select();
        $this->assign("data", $Department);
        $Department = $this->consignee_model->field("department_id")->where(array('consignee_type' => 1, 'belong_to' => 1, 'table_id' => $id))->select();
        $result = array();
        foreach ($Department as $key => $vo) {
            $result[] = $vo['department_id'];
            $this -> assign('selectDefault',$vo['department_id']);
        }
        $this->assign("dept1", json_encode($result));


        $Department = $this->consignee_model->field("department_id")->where(array('consignee_type' => 2, 'belong_to' => 1, 'table_id' => $id))->select();
        $result = array();
        foreach ($Department as $key => $vo) {
            $result[] = $vo['department_id'];
        }

        $this->assign("dept2", json_encode($result));

        //picture
        $this->editFileDisplay(17);
    }

}

?>